/*
 * @Author: Yuluo 568055454@qq.com
 * @Date: 2023年06月17日 19:56:48
 * @LastEditors: Yuluo 568055454@qq.com
 * @LastEditTime: 2023年07月16日 03:36:53
 * @FilePath: \Mood-Blog-System\back\middlewares\AuthMiddleware\index.js
 * @Description: AuthMiddleware中间件，用于验证用户身份，判断用户是否登录，以及用户是否有权限访问某些资源，
 * 请求头的Promission用于判断是否需要开启权限校验，如果不需要，则不会进行token校验，直接通过
 * Copyright (c) 2023 by Yuluo, All Rights Reserved. 
 */
const { verifyToken, signToken } = require('../../util/jwt');
const logger = require('../../log4');
const { logTemplate, accessLogTemplate } = require('../../util/log4js')

function authMiddleware(ctx, next) {
    // if (!ctx.get('Promission')) return next();
    const authMethods = ['POST', , 'DELETE', 'PUT'];
    const urlArr = ctx.url.split('/');
    const token = ctx.get('Authorization') || ctx?.query?.Authorization || ctx.request?.body?.Authorization;

    if (urlArr.includes('register')) return next();
    if (!(authMethods.includes(ctx.method) || urlArr.includes('user') || urlArr.includes('login'))) {
        const { data, error } = verifyToken(token);
        if (!error) ctx.user = data;
        return next();
    };

    if (!!token) {
        const { data, error } = verifyToken(token);
        if (error) {
            console.log('token验证失败，请重新登录');
            ctx.body = { message: 'token验证失败，请重新登录！', code: 4000 }
            logger('access').error(logTemplate(
                [ctx.body, accessLogTemplate(ctx)]
            ))
            return;
        } else {
            ctx.user = data;
            console.log('token验证成功', data);
            logger('access').info(accessLogTemplate(ctx, { user: data }))
            return next();
        }
    } else {
        console.log('未发现token，请先登录');
        ctx.body = { message: '未发现token，请先登录！', code: 4000 }
        logger('access').error(logTemplate(
            [ctx.body, accessLogTemplate(ctx)]
        ))
        return;
    }
}

module.exports = authMiddleware;